// 存储用户token持久化
import { getUserInfo } from '@/api/user'
import { Toast } from 'vant'
import {
  setStorageToken,
  getStorageToken,
  removeStorageToken
} from '@/utils/storage'
// !本地存储代码单独进行封装放到工具文件夹里
export default {
  state: {
    token: getStorageToken(),
    userInfo: {}
  },
  getters: {},
  mutations: {
    setToken(state, payload) {
      state.token = payload
      setStorageToken(payload)
    },
    removeToken(state) {
      state.token = {}
      removeStorageToken()
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    }
  },
  actions: {
    // !异步ajax放到actions中，commit时需要带上数据给到userInfo对象里面，从而传到个人中心界面使用 这里需要捕获异常try/catch
    async getUserInfoAsync(context) {
      try {
        const res = await getUserInfo()
        // console.log(res.data)
        context.commit('setUserInfo', res.data)
      } catch {
        Toast('获取用户信息失败')
      }
    }
  },
  namespaced: true
}
